package indi.wshape1.takeawaydeliveryinfo.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import indi.wshape1.takeawaydeliveryinfo.dao.impl.BaseDAOImpl;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Wshape1
 * @create 2022-12-09 18:04
 */

public class ConnectionUtil {

    private static final DataSource dataSource;
    private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        try {
            Properties properties = new Properties();
            properties.load(BaseDAOImpl.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection getConnection() {
        try {
            if (threadLocal.get() == null || threadLocal.get().isClosed()) {

                threadLocal.set(getDataSource().getConnection());

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return threadLocal.get();
    }

    public static void closeConnection() throws SQLException {
        Connection conn = threadLocal.get();
        if (conn == null) {
            return;
        }
        if (!conn.isClosed()) {
            conn.close();
            threadLocal.set(null);
        }
    }

}
